//
//  TFPhotoScrollView.m
//  PhotoDemoProject
//
//  Created by TFAppleWork-Summer on 2016/11/22.
//  Copyright © 2016年 TFAppleWork-Summer. All rights reserved.
//

#import "TFPhotoScrollView.h"

@interface TFPhotoScrollView ()<UIScrollViewDelegate>

@property (nonatomic, strong, readwrite) UIImageView *zoomImageView;


@end

@implementation TFPhotoScrollView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.bouncesZoom = YES;
        self.decelerationRate = UIScrollViewDecelerationRateFast;
        self.delegate = self;
        [self addSubview:self.zoomImageView];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    //让imageView居中
    CGSize boundsSize = self.bounds.size;
    CGRect frameToCenter = _zoomImageView.frame;
    
    // center horizontally
    if (frameToCenter.size.width < boundsSize.width)
    frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
    else
    frameToCenter.origin.x = 0;
    
    // center vertically
    if (frameToCenter.size.height < boundsSize.height)
    frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
    else
    frameToCenter.origin.y = 0;
    
    _zoomImageView.frame = frameToCenter;
}

- (void)p_calculateMinAndMaxScales {
    CGFloat height = CGRectGetHeight(self.frame);
    CGFloat width = CGRectGetWidth(self.frame);
    CGFloat xScale = width/self.zoomImageView.image.size.width;
    CGFloat yScale = height/self.zoomImageView.image.size.height;
    CGFloat minScale = 1.0;
    CGFloat maxScale = 1.0;
    if ((xScale<1.0)|(yScale<1.0)) {
        //大图
        maxScale = 1.0;
        minScale = MIN(xScale, yScale);
    }
    else {
        //小图
        minScale = 1.0;
        maxScale = MAX(xScale, yScale);
    }
    self.minimumZoomScale = minScale;
    self.maximumZoomScale = maxScale;
    self.zoomScale = minScale;
}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.zoomImageView;
}

#pragma mark - lazy load.

- (void)setImage:(UIImage *)image {
    _image = image;
    self.zoomImageView.image = image;
    [self.zoomImageView sizeToFit];
    self.contentSize = image.size;
    [self p_calculateMinAndMaxScales];
    self.zoomImageView.center = self.center;
}

- (UIImageView *)zoomImageView {
    if (!_zoomImageView) {
        _zoomImageView = [[UIImageView alloc] init];
        _zoomImageView.userInteractionEnabled = YES;
    }
    return _zoomImageView;
}

@end
